'use strict';

const Controller = require('egg').Controller;

/**
 * 人员项目组关系控制器
 * 处理人员和项目组之间的关联关系管理
 */
class PersonProjectGroupController extends Controller {
  /**
   * 获取人员所属的项目组列表
   * @param {Object} ctx.request.body
   * @param {number} ctx.request.body.person_id - 人员ID
   */
  async getGroupsByPersonId() {
    const { ctx } = this;
    ctx.validate({
      person_id: { type: 'number', required: true },
    });

    const { person_id } = ctx.request.body;
    const groups = await ctx.service.personProjectGroup.getGroupsByPersonId(person_id);
    ctx.body = groups;
  }

  /**
   * 获取项目组的成员列表
   * @param {Object} ctx.request.body
   * @param {number} ctx.request.body.project_group_id - 项目组ID
   */
  async getPersonsByGroupId() {
    const { ctx } = this;
    ctx.validate({
      project_group_id: { type: 'number', required: true },
    });

    const { project_group_id } = ctx.request.body;
    const persons = await ctx.service.personProjectGroup.getPersonsByGroupId(project_group_id);
    ctx.body = persons;
  }

  /**
   * 添加人员到项目组
   * @param {Object} ctx.request.body
   * @param {number} ctx.request.body.person_id - 人员ID
   * @param {number} ctx.request.body.project_group_id - 项目组ID
   * @throws {422} 人员已在项目组中时抛出异常
   */
  async addPersonToGroup() {
    const { ctx } = this;
    ctx.validate({
      person_id: { type: 'number', required: true },
      project_group_id: { type: 'number', required: true },
    });

    const { person_id, project_group_id } = ctx.request.body;
    const result = await ctx.service.personProjectGroup.addPersonToGroup(person_id, project_group_id);

    if (result.error === 'already_exists') {
      ctx.throw(422, '该人员已在项目组中');
    }

    ctx.body = result;
  }

  /**
   * 从项目组移除人员
   * @param {Object} ctx.request.body
   * @param {number} ctx.request.body.person_id - 人员ID
   * @param {number} ctx.request.body.project_group_id - 项目组ID
   */
  async removePersonFromGroup() {
    const { ctx } = this;
    ctx.validate({
      person_id: { type: 'number', required: true },
      project_group_id: { type: 'number', required: true },
    });

    const { person_id, project_group_id } = ctx.request.body;
    const result = await ctx.service.personProjectGroup.removePersonFromGroup(person_id, project_group_id);
    ctx.body = result;
  }
}

module.exports = PersonProjectGroupController; 